using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdminDto.Common;
using AvalonAdminDto.Sys.AdminDtos;
using D.UtilCore.Dtos;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace AvalonAdmin.Pages.Sys.ViewModels
{
    /// <summary>
    /// 用户修改视图模型，专门用于用户添加和编辑功能
    /// </summary>
    public class UserModifyViewModel : BaseModifyViewModel
    {
        #region 页面属性及初始化数据

        private string? _id;
        public UserModifyViewModel(string? id = null, ViewStatus? viewStatus = ViewStatus.Add) : base()
        {
            _id = id;
            _currentUser = new RepAdminInfo();
            if (viewStatus == ViewStatus.View)
            {// 查看详情
                IsEnabled = false; //禁用所有输入
                IsEditVisibility = true; // 所有都显示
                IsHistoryVisibility = true; 
            }
            else if(viewStatus == ViewStatus.Add)
            {// 新增
                IsEnabled = true; // 所有显示的都可以输入
                IsEditVisibility = true;// 所有都显示
                IsHistoryVisibility = false;// 其他部分字段不显示
            }
            else
            {// 修改
                IsEnabled = true; // 所有显示的都可以输入
                IsEditVisibility = false;// 部分不能显示(密码，二次密码)
                IsHistoryVisibility = false;// 其他部分字段不显示
            }

            // 如果有ID，则加载数据
            if (!string.IsNullOrEmpty(_id))
            {
                _ = Task.Run(async () => await QueryAsync());
            }
        }

        /// <summary>
        /// 查询数据（用于刷新当前用户数据）
        /// </summary>
        public override async Task<bool> QueryAsync()
        {
            if (!string.IsNullOrEmpty(_id))
            {
                try
                {
                    var res = await HttpHelper<RepAdminInfo>.GetAsync($"{ApiUrl.GetAdmin}/{_id}");

                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        _id = res.Data.Id;
                        CurrentUser = new RepAdminInfo
                        {
                            Id = res.Data.Id,
                            UUID = res.Data.UUID,
                            Account = res.Data.Account,
                            NickName = res.Data.NickName,
                            Email = res.Data.Email,
                            Phone = res.Data.Phone,
                            Status = res.Data.Status,
                            Description = res.Data.Description,
                            CreateUser = res.Data.CreateUser,
                            CreateTime = res.Data.CreateTime,
                            UpdateUser = res.Data.UpdateUser,
                            UpdateTime = res.Data.UpdateTime
                        };

                        // 编辑模式下不显示密码字段
                        Password = string.Empty;
                        PasswordConfirm = string.Empty;
                    }
                    else if (res.Code == StatusCodeEnum.Waring)
                    {
                        ShowWarning(res.Msg);
                    }
                    else
                    {
                        ShowError(res.Msg ?? "加载用户数据失败");
                    }
                }
                catch (System.Exception ex)
                {
                    ShowError($"加载用户数据失败：{ex.Message}");
                }
            }
            return true;
        }

        #endregion

        #region 数据编辑属性

        private RepAdminInfo _currentUser;

        /// <summary>
        /// 当前用户信息
        /// </summary>
        public RepAdminInfo CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        /// <summary>
        /// 密码（仅用于新增和修改密码）
        /// </summary>
        [MinLength(6, ErrorMessage = "密码长度不能少于6位")]
        [MaxLength(20, ErrorMessage = "密码长度不能超过20位")]
        [Required(ErrorMessage = "密码不能为空")]
        public string? Password { get; set; }

        /// <summary>
        /// 确认密码
        /// </summary>
        [MinLength(6, ErrorMessage = "确认密码长度不能少于6位")]
        [MaxLength(20, ErrorMessage = "确认密码长度不能超过20位")]
        [Required(ErrorMessage = "确认密码不能为空")]
        public string? PasswordConfirm { get; set; }

        #endregion 

        #region 提交，重置

        /// <summary>
        /// 提交表单数据
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 验证输入参数
                if (!ValidateInput())
                {
                    return;
                }

                if (string.IsNullOrEmpty(_id))
                {
                    var res = await HttpHelper<int>.PostAsync(ApiUrl.AddAdmin, new ReqAddAdmin()
                    {
                        UUID = CurrentUser.UUID,
                        NickName = CurrentUser.NickName,
                        Account = CurrentUser.Account,
                        Pwd = Password,
                        Email = CurrentUser.Email,
                        Phone = CurrentUser.Phone,
                        Status = CurrentUser.Status,
                        Description = CurrentUser.Description
                    });

                    HandleApiResponse(res, "添加成功", "添加失败");
                }
                else
                {
                    // 修改用户
                    var res = await HttpHelper<int>.PutAsync($"{ApiUrl.UpdateAdmin}/{_id}", new ReqUpdateAdmin()
                    {
                        Id = _id,
                        UUID = CurrentUser.UUID,
                        NickName = CurrentUser.NickName,
                        Email = CurrentUser.Email,
                        Phone = CurrentUser.Phone,
                        Status = CurrentUser.Status,
                        Description = CurrentUser.Description
                    });
                    HandleApiResponse(res, "修改成功", "修改失败");
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 验证输入参数
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateInput()
        {
            if (string.IsNullOrEmpty(CurrentUser.Account))
            {
                ShowWarning("账户名不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(_id))
            {
                if (string.IsNullOrEmpty(Password))
                {
                    ShowWarning("密码不能为空");
                    return false;
                }

                if (string.IsNullOrEmpty(PasswordConfirm))
                {
                    ShowWarning("确认密码不能为空");
                    return false;
                }

                if (Password != PasswordConfirm)
                {
                    ShowWarning("密码和确认密码不一致");
                    return false;
                }
            }

            if (string.IsNullOrEmpty(CurrentUser.NickName))
            {
                ShowWarning("昵称不能为空");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            CurrentUser = new RepAdminInfo
            {
                Status = true
            };
            Password = string.Empty;
            PasswordConfirm = string.Empty;
        }

        #endregion
    }
}
